const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const pool = require("../config/db");

// 登录接口
router.post("/login", async (req, res) => {
  try {
    const { username, password } = req.body;

    // 参数验证
    if (!username || !password) {
      return res.status(400).json({
        code: 400,
        message: "用户名和密码不能为空"
      });
    }

    // 查询用户
    const [users] = await pool.execute("SELECT * FROM users WHERE username = ?", [username]);

    // 用户不存在
    if (users.length === 0) {
      return res.status(401).json({
        code: 401,
        message: "用户名或密码不正确"
      });
    }

    const user = users[0];

    // 验证密码
    let isPasswordValid = true;
    if (password !== user.password) {
      isPasswordValid = false;
    }
    if (password !== user.password) {
      isPasswordValid = false;
    }
    // console.log(isPasswordValid,user.password,password);

    if (!isPasswordValid) {
      return res.status(401).json({
        code: 401,
        message: "用户名或密码不正确"
      });
    }

    // 获取用户角色
    const [userRoles] = await pool.execute(
      `
      SELECT r.id, r.name, r.code 
      FROM roles r
      INNER JOIN user_roles ur ON r.id = ur.role_id
      WHERE ur.user_id = ?
    `,
      [user.id]
    );

    // 生成Token
    const token = jwt.sign(
      {
        id: user.id,
        username: user.username,
        roles: userRoles.map((role) => role.code)
      },
      process.env.JWT_SECRET,
      { expiresIn: "24h" }
    );

    // 返回用户信息和Token
    res.json({
      code: 200,
      message: "登录成功",
      success: true,
      token: token,
      userInfo: {
        id: user.id,
        username: user.username,
        name: user.name,
        roles: userRoles
      }
    });
  } catch (error) {
    console.error("登录错误:", error);
    res.status(500).json({
      code: 500,
      message: "服务器内部错误"
    });
  }
});

// 验证Token的中间件
const verifyToken = (req, res, next) => {
  const token = req.headers.authorization;

  if (!token) {
    return res.status(401).json({
      code: 401,
      message: "未提供授权令牌"
    });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (error) {
    return res.status(401).json({
      code: 401,
      message: "无效的授权令牌"
    });
  }
};

// 检查角色权限中间件
const checkRolePermission = (permissionCode) => {
  return async (req, res, next) => {
    try {
      const userRoles = req.user.roles;

      // 如果用户是管理员角色，直接通过
      if (userRoles.includes("admin")) {
        return next();
      }

      // 获取当前用户角色所拥有的所有权限
      const roleIds = await getRoleIdsByCode(userRoles);
      if (roleIds.length === 0) {
        return res.status(403).json({
          code: 403,
          message: "您没有权限执行此操作"
        });
      }

      // 检查角色是否拥有指定的权限码
      const [permissions] = await pool.execute(
        `
        SELECT DISTINCT m.permission_code
        FROM menus m
        INNER JOIN role_menus rm ON m.id = rm.menu_id
        WHERE rm.role_id IN (?) AND m.permission_code = ?
      `,
        [roleIds, permissionCode]
      );
      console.log(permissions, "permissions");
      if (permissions.length === 0) {
        return res.status(403).json({
          code: 403,
          message: "您没有权限执行此操作"
        });
      }

      next();
    } catch (error) {
      console.error("权限检查错误:", error);
      res.status(500).json({
        code: 500,
        message: "服务器内部错误"
      });
    }
  };
};

// 根据角色代码获取角色ID
const getRoleIdsByCode = async (roleCodes) => {
  if (!roleCodes || roleCodes.length === 0) {
    return [];
  }

  const placeholders = roleCodes.map(() => "?").join(",");
  const [roles] = await pool.execute(`SELECT id FROM roles WHERE code IN (${placeholders})`, roleCodes);

  return roles.map((role) => role.id).join(",");
};

module.exports = router;
module.exports.verifyToken = verifyToken;
module.exports.checkRolePermission = checkRolePermission;
